//
//  ZJDynamicViewController.m
//  LovingPartyBuilding
//
//  Created by ZJ on 2017/6/6.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "ZJDynamicViewController.h"
#import "ZJRefurbish.h"
#import "ZJDynamicSectonView.h"
#import "ZJDynamicCommentTableViewCell.h"
#import "ZJDynamicLickTableViewCell.h"
#import "SendCommentView.h"
#import <IQKeyboardManager.h>
#import "ZJSendMessageView.h"
#import "LPActivityDetailPublishTellViewController.h"

#define Comment_CELLID @"ZJDynamicCommentTableViewCell"
#define Like_CELLID @"ZJDynamicLickTableViewCell"
#define SECTIONID @"ZJDynamicSectonView"

@interface ZJDynamicViewController ()<UITableViewDelegate,UITableViewDataSource,ZJDynamicSectonViewDelegate,CSGrowingTextViewDelegate,ZJSendMessageViewDelegate>
{
    NSInteger _isfirst;
    UIView *_commentBGView;/** 评论页面背景View */
    
    NSInteger _index;/**< 记录需要刷新的sectionView */
    ///判断是不是cell点击的评论 YES表示是cell NO表示是sectionView上面的评论按钮
    BOOL isComment_Cell;
    ///发表评论需要的数据 (是sectionView上面的评论按钮的数据)
    ZJTalkModel *commentData_Talk;
    ///发表评论需要的数据 (是点击cell的数据)
    ZJCommentList *commentData_Comment;
    /**  判断是否删除过  */
    BOOL isDelete;
}
/** 滑动 */
@property (nonatomic, strong) ZJRefurbish *refurbish;
/** tableview */
@property (nonatomic, strong) UITableView *tableView;
/** 数组 */
@property (nonatomic, strong) NSMutableArray *dataArray;
/** 评论模块 */
@property (nonatomic, strong) ZJSendMessageView *sendCommentView;
/**  分页  */
@property (assign, nonatomic) NSInteger  page;
@end

@implementation ZJDynamicViewController

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    
    if (self.block) {
        self.block();
    }
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titlelabel.text = @"活动圈";
    __weak typeof(self) weakSelf = self;
    [self.refurbish headerToScollview:self.tableView Block:^{
        weakSelf.page = 1;
        [weakSelf netWroking_Header];
    }];
    [self.refurbish footerToScollview:self.tableView Block:^{
//        _page ++;
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
    [self.tableView.mj_header beginRefreshing];
    [self setupUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];/**< 键盘将要出现的通知 */
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object:nil];/**< 键盘将要消失的通知 */
    

}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setupUI{
    self.rightButton.hidden = NO;
    [self.rightButton setImage:[UIImage imageNamed:@"home_btn_more"] forState:UIControlStateNormal];
    
    [self.view addSubview:self.tableView];
    
    _commentBGView = [[UIView alloc] initWithFrame:self.view.bounds];
    _commentBGView.backgroundColor = [UIColor blackColor];
    _commentBGView.alpha = 0.2;
    _commentBGView.hidden = YES;
    UITapGestureRecognizer *tapGester = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(action_tapGester)];
    [_commentBGView addGestureRecognizer:tapGester];
    [self.view addSubview:_commentBGView];
    [self.view addSubview:self.sendCommentView];
}




#pragma mark - 网络请求
//请求所有说说数据接口
- (void)netWroking_Header{
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{@"ACT_ID": self.model.ID,
                           @"PAGESTART":[NSString stringWithFormat:@"%ld",(long)_page],
                           @"PAGECOUNT":@"15"};
    [NetWorkingManager postWithUrlString:[NetWorkingURL getChatList] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            ZJDyamicModel *model1 = [ZJDyamicModel yy_modelWithJSON:object];
            weakSelf.dataArray = [model1.CHILDREN_MODEL mutableCopy];
            [weakSelf.tableView reloadData];
        }
        [weakSelf.tableView.mj_header endRefreshing];
    } Fail:^(id object) {
        [weakSelf.tableView.mj_header endRefreshing];
    }];

}

//请求某个说说数据接口
- (void)netWorking_nolyChat_index:(NSInteger)index{
    __weak typeof(self) weakSelf = self;
    ZJTalkModel *model = self.dataArray[index];
    NSDictionary *dict = @{@"PID":model.ID};
    [NetWorkingManager postWithUrlString:[NetWorkingURL getOnlyList] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {
            ZJDyamicModel *dyamicModel = [ZJDyamicModel yy_modelWithJSON:object];
            weakSelf.dataArray[index] = dyamicModel.CHILDREN_MODEL[0];
            
            [weakSelf.tableView reloadData];
        }
    } Fail:^(id object) {
        
    }];

}

#pragma mark - 点击事件———发表说说
- (void)action_rightButton:(UIButton *)sender{
    LPActivityDetailPublishTellViewController *vc = [LPActivityDetailPublishTellViewController new];
    vc.model = self.model;
    vc.block = ^{
        [self.tableView.mj_header beginRefreshing];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 键盘处理

- (void)action_tapGester{
    [self.view endEditing:YES];
    
}

- (void)keyboardWillShow:(NSNotification *)notification {
    _commentBGView.hidden = NO;
    self.sendCommentView.hidden = NO;
    [self.view bringSubviewToFront:self.sendCommentView];
    
    CGFloat curkeyBoardHeight = [[[notification userInfo] objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue].size.height;
    
    NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //计算 视图应该移动的位置
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:interal animations:^{
        
        weakSelf.sendCommentView.frame = CGRectMake(0, [UIScreen zj_screenHeight] - weakSelf.sendCommentView.height - curkeyBoardHeight, [UIScreen zj_screenWith], weakSelf.sendCommentView.height);
    }];
}

- (void)keyboardWillDismiss:(NSNotification *)notification {
    _commentBGView.hidden = YES;
    self.sendCommentView.hidden = YES;
    NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //计算 视图应该移动的位置
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:interal animations:^{
        weakSelf.sendCommentView.frame = CGRectMake(0, [UIScreen zj_screenHeight], [UIScreen zj_screenWith], weakSelf.sendCommentView.height);
        
    }];
}


#pragma mark - ZJDynamicSectonViewDelegate 协议方法
- (void)ZJDynamicSectonViewDelegate_DeleteSuccess_index:(NSInteger)index{
    isDelete = YES;
    [self.dataArray removeObjectAtIndex:index];
    [self.tableView reloadData];
}
- (void)ZJDynamicSectonViewDelegate_operationSuccess_index:(NSInteger)index{
    [self netWorking_nolyChat_index:index];
}

- (void)ZJDynamicSectonViewDelegate_commentClick_index:(NSInteger)index{
    self.sendCommentView.growingTextView.placeholderLabel.text = @"发表评论...";
    _index = index;
    isComment_Cell = NO;
    commentData_Talk = self.dataArray[index];
    [self.sendCommentView.growingTextView.internalTextView becomeFirstResponder];
    
}
#pragma mark - CSGrowingTextViewDelegate 协议方法
- (void)growingTextView:(CSGrowingTextView *)growingTextView willChangeHeight:(CGFloat)height{
    height = height > 34 ? height :34;
    
    CGFloat viewHeight = height + 15;
    self.sendCommentView.frame = CGRectMake(self.sendCommentView.x, self.sendCommentView.bottom - viewHeight , self.sendCommentView.width, viewHeight);
}

- (BOOL)growingTextView:(CSGrowingTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSString * toBeString = [textView.internalTextView.text stringByReplacingCharactersInRange:range withString:text];
    
    if (toBeString.length >= 200 && range.length!= 1 ){
        textView.internalTextView.text = [toBeString substringToIndex:200];
        return NO;
    }
    return YES;
}


#pragma mark - ZJSendMessageViewDelegate 协议方法
//发送评论
- (void)sendMessageWithView:(ZJSendMessageView *)view message:(NSString *)message{
    if (message.length > 0) {
        [self netWorking_comment];
    }
    [self.view endEditing:YES];
    
}
///评论的网络请求
- (void)netWorking_comment{
   
    NSString *FID;
    NSString *CHAT_ID;
    
    if (isComment_Cell) {//点击cell
        FID = commentData_Comment.ACTCON_ID;
        CHAT_ID = commentData_Comment.PID;
    }else{//点击sectionView
        FID = @"0";
        CHAT_ID = commentData_Talk.PID;
    }
     [YJProgressHUD show:@"评论中..." inView:self.view mode:YJProgressModeLoading];
    NSDictionary *dict = @{
                           @"FID":FID,
                           @"CHAT_ID":CHAT_ID,
                           @"USERID":[ZJUserInfoModel sharedUserInfo].ORG_ACCOUNT.ID,
                           @"CONTENT":self.sendCommentView.growingTextView.internalTextView.text,
                           };
    __weak typeof(self) weakSelf = self;
    [NetWorkingManager postWithUrlString:[NetWorkingURL addCommintDymaic] Parameter:dict Success:^(id object) {
        
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        if ([model.STATE isEqualToString:@"20000"]) {//成功
            [YJProgressHUD showMsgWithoutView:@"评论成功"];
        
            [weakSelf netWorking_nolyChat_index:_index];
        }else{
            [YJProgressHUD showMsgWithoutView:@"评论失败"];
        
        }
    } Fail:^(id object) {
        [YJProgressHUD showMsgWithoutView:@"评论失败"];
    }];
}

#pragma mark - UITableView 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    ZJTalkModel *model = self.dataArray[section];
    if (model.PARISELIST || model.PARISELIST.count > 0) {
        return  model.COMMENTLIST.count + 1;
    }
    return  model.COMMENTLIST.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    ZJDynamicSectonView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:SECTIONID];
    view.section = section;
    view.model = self.dataArray[section];
    view.delegate = self;
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZJTalkModel *model = self.dataArray[indexPath.section];
    if (indexPath.row == 0) {//是第一个
        if (model.PARISELIST && model.PARISELIST.count > 0) {//点赞存在
            ZJDynamicLickTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Like_CELLID forIndexPath:indexPath];
            if (model.COMMENTLIST.count > 0) {//有评论
                cell.haveComment = YES;
            }else{
                cell.haveComment = NO;
            }
            cell.likeArray = model.PARISELIST_MODEL;
            return cell;
        }else{//点赞不存在
            ZJDynamicCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Comment_CELLID forIndexPath:indexPath];
            cell.indexPath = indexPath;
            cell.talkModel = model;
            cell.model = model.COMMENTLIST_MODEL[indexPath.row];
            return cell;
        }
    }else{//不的第一个
        ZJDynamicCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Comment_CELLID forIndexPath:indexPath];
        cell.indexPath = indexPath;
        cell.talkModel = model;
         if (model.PARISELIST && model.PARISELIST.count > 0) {//点赞存在
             cell.model = model.COMMENTLIST_MODEL[indexPath.row - 1];
         }else{//点赞不存在
             cell.model = model.COMMENTLIST_MODEL[indexPath.row];
         }
        
        
        return cell;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    ZJTalkModel *model = self.dataArray[section];
    return model.sectionViewHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZJTalkModel *model = self.dataArray[indexPath.section];
    model.indexPath = indexPath;
    if (model.PARISELIST && model.PARISELIST.count > 0 && indexPath.row == 0) {//点赞cell
        return model.likeCellHeight;
    }else{
        return model.commentCellHeight;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.000001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _index = indexPath.section;
    ZJTalkModel *model = self.dataArray[indexPath.section];
    if ((model.PARISELIST || model.PARISELIST.count > 0) && indexPath.row == 0) {//点击的是点赞模块
        
    }else{//点击的是评论模块
        isComment_Cell = YES;
        if (model.PARISELIST || model.PARISELIST.count > 0) {//有点赞数据
            commentData_Comment = model.COMMENTLIST_MODEL[indexPath.row - 1];
        }else{
            commentData_Comment = model.COMMENTLIST_MODEL[indexPath.row];
        }
        if ([commentData_Comment.USERID isEqualToString:ZJUSERINFORMODEL.ORG_ACCOUNT.ID]) {
            [YJProgressHUD showMessage:@"不能评论自己" inView:self.view];
            return;
        }
        self.sendCommentView.growingTextView.placeholderLabel.text = [NSString stringWithFormat:@"回复%@...",commentData_Comment.UNAME];
        [self.sendCommentView.growingTextView.internalTextView becomeFirstResponder];
    }
}

#pragma mark - Setter
#pragma mark - Getters
- (UITableView *)tableView{
    if (_tableView == nil){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LP_TopHeight, self.view.width, [UIScreen zj_screenHeight] - LP_TopHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [_tableView registerClass:[ZJDynamicCommentTableViewCell class] forCellReuseIdentifier:Comment_CELLID];
        [_tableView registerClass:[ZJDynamicLickTableViewCell class] forCellReuseIdentifier:Like_CELLID];
        [_tableView registerClass:[ZJDynamicSectonView class] forHeaderFooterViewReuseIdentifier:SECTIONID];
    }
    return _tableView;
}

- (ZJRefurbish *)refurbish{
    if (_refurbish == nil){
        _refurbish = [ZJRefurbish new];
        
    }
    return _refurbish;
}

- (NSMutableArray *)dataArray{
    if (_dataArray == nil){
        _dataArray = [NSMutableArray array];
        
    }
    return _dataArray;
}
- (ZJSendMessageView *)sendCommentView{
    if (_sendCommentView == nil){
        _sendCommentView = [[ZJSendMessageView alloc]init];
        _sendCommentView.frame = CGRectMake(0, [UIScreen zj_screenHeight], [UIScreen zj_screenWith], 49);
        _sendCommentView.delegate = self;
        _sendCommentView.growingTextView.placeholderLabel.text = @"发表评论...";
    }
    return _sendCommentView;
}

@end
